<template>
  <div class="apply-score">
    <el-form v-loading="loading" label-width="80px">
      <el-form-item label="姓名" prop="studentName">
        <el-input disabled v-model="name"></el-input>
      </el-form-item>
      <el-form-item label="学号" prop="studentID">
        <el-input disabled v-model="studentId"></el-input>
      </el-form-item>
      <el-form-item label="积分事项" prop="integralContent">
        <el-select v-model="eventId" filterable placeholder="请选择">
          <el-option v-for="item in eventOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="积分" prop="Integral">
        <el-input v-model="score" :disabled="eventId !== 1" placeholder="请输入积分，例如-1，+2等"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="apply-score-submit-button" @click="handleSubmitApply">确 定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import api from "@/api";
import idMapper from "@/utils/idMapper";
export default {
  data() {
    return {
      loading: false,
      name: "",
      studentId: "",
      events: [],
      eventId: 1,
      score: 0,
    };
  },
  computed: {
    eventOptions() {
      return this.events.map((val) => {
        return {
          value: val.id,
          label: val.description
        };
      });
    },
    eventsIDMapper() {
      return idMapper(this.events);
    }
  },
  watch: {
    "$route"(to) {
      this.updateFormData();
    },
    eventId(id) {
      this.score = this.eventsIDMapper[id].score;
    }
  },
  created() {
    this.updateFormData();
    this.getEvents();
  },
  methods: {
    async getEvents() {
      const { data } = await api.getEvents();
      this.events = data.data;
    },

    async updateFormData() {
      if (this.$route.path.indexOf("apply-score/") === -1) {
        return;
      }
      const studentId = this.$route.params.id || "";

      this.loading = true;
      try {
        const { data } = await api.getMember({
          studentId
        });
        this.name = data.data.name;
        this.studentId = studentId;
      } catch (error) {
        this.$message.error("无权进行此操作");
      }
      this.loading = false;
    },
    async handleSubmitApply() {
      let reqData = {
        studentId: this.studentId,
        eventId: this.eventId,
        score: this.score
      };
      if (this.eventId !== 1) {
        delete reqData.score;
      }
      console.log();
      try {
        const { data } = await api.addEventRecord({
          ...reqData
        });
        this.$emit("submit");
        this.$message.success("提交成功");
      } catch (error) {
        this.$message.success("提交失败");
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.apply-score {
  width: 600px;
}
</style>

